package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.ItemStatusConstants;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.OrderDetailInfo;
import com.cskaoyan.order.dto.OrderItemDto;
import com.cskaoyan.order.dto.OrderListResponse;
import com.cskaoyan.order.dto.OrderShippingDto;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.form.OrderListRequest;
import com.cskaoyan.order.service.OrderCoreService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter orderConverter;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }


    /***
     * 取消订单
     * @param orderId
     */
    @Override
    public void cancelOrder(String orderId) {

        // 将该订单对应的所有商品的冻结库存释放
        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

        //List<OrderItem> orderItems = orderItemMapper.selectOrderItemByOrderId(orderId.trim());

        for (OrderItem orderItem : orderItems) {
            Stock stock = new Stock(orderItem.getItemId(), orderItem.getNum().longValue(), (-orderItem.getNum()));

            try {
                stockMapper.updateStock(stock);
                // 修改订单商品表中的状态为已经释放
                orderItemMapper.updateStockStatus(ItemStatusConstants.STOCK_RELEASE, orderId);


                // 修改订单状态为已取消，更新订单更新时间，交易完成时间，交易关闭时间
                Order order = new Order();

                order.setOrderId(orderId);
                order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);

                Date date = new Date();
                order.setUpdateTime(date);
                order.setEndTime(date);
                order.setCloseTime(date);

                orderMapper.updateByPrimaryKeySelective(order);
            } catch (Exception e) {
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
                        OrderRetCode.DB_EXCEPTION.getMessage());
            }

        }


    }

    @Override
    public void deleteOrder(String orderId) {
        // 如果要删除订单，那么订单的状态应该是 5交易关闭 6交易失败 7-订单取消'

        // 先查订单的状态
        Order order = orderMapper.selectByPrimaryKey(orderId);

        Integer status = order.getStatus();

        if (status == OrderConstants.ORDER_STATUS_TRANSACTION_CLOSE
                || status == OrderConstants.ORDER_STATUS_TRANSACTION_FAILED ||
                status == OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL) {
            // 对应这三种状态，可以删除
            orderMapper.deleteByPrimaryKey(orderId);
        } else {
            throw new BizException(OrderRetCode.ORDER_NOT_DELETE.getCode(), OrderRetCode.ORDER_NOT_DELETE.getMessage());

        }


    }

    @Override
    public void updateOrder(Integer status, String orderId) {

        // 更新订单状态，更新时间
        Order order = new Order();
        order.setStatus(status);
        order.setOrderId(orderId);

        Date date = new Date();
        order.setUpdateTime(date);
        order.setPaymentTime(date);

        orderMapper.updateByPrimaryKeySelective(order);

        // 查询该订单对应的库存信息

        Example example = new Example(OrderItem.class);

        example.createCriteria().andEqualTo("orderId", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

        for (OrderItem orderItem : orderItems) {
            Stock stock = new Stock();
            stock.setItemId(orderItem.getItemId());
            stock.setStockCount(0L);
            stock.setLockCount(-orderItem.getNum());
            stockMapper.updateStock(stock);

            // 修改订单商品表的状态为库存扣减成功
            orderItemMapper.updateStockStatus(ItemStatusConstants.STOCK_SUB_SUCCESS, orderItem.getOrderId());

        }




    }


    @Override
    public OrderListResponse allOrder(OrderListRequest orderListRequest) {

        Example example = new Example(Order.class);


        example.createCriteria().andEqualTo("userId", orderListRequest.getUserId());


        example.setOrderByClause("update_time desc");

        // 开启分页
        PageHelper.startPage(orderListRequest.getPage(), orderListRequest.getSize());
        List<Order> orders = orderMapper.selectByExample(example);

        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);

        // 如果订单不为空，则查询该订单对应的商品信息

        List<OrderDetailInfo> orderDetailInfos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orders)) {
            for (Order order : orders) {

                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);

                // 查询该订单对应的商品信息
                Example example1 = new Example(OrderItem.class);
                example1.createCriteria().andEqualTo("orderId", order.getOrderId());

                List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);

                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

                // 查询邮寄信息
                Example example2 = new Example(OrderShipping.class);

                example2.createCriteria().andEqualTo("orderId",order.getOrderId());

                List<OrderShipping> orderShippings = orderShippingMapper.selectByExample(example2);

                if (CollectionUtils.isEmpty(orderShippings)) {
                    throw new BizException(OrderRetCode.SHIPPING_DB_QUERY_FAILED.getCode(),
                            OrderRetCode.SHIPPING_DB_QUERY_FAILED.getMessage());
                }


                orderDetailInfo.setOrderItemDto(orderItemDtos);
                if (!CollectionUtils.isEmpty(orderShippings)) {
                    OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShippings.get(0));

                    orderDetailInfo.setOrderShippingDto(orderShippingDto);
                }
                orderDetailInfos.add(orderDetailInfo);

            }

        }

        // 如果订单不为空，则查询该订单对应的邮寄地址信息

        OrderListResponse orderListResponse = new OrderListResponse();

        orderListResponse.setTotal(orderPageInfo.getTotal());
        orderListResponse.setData(orderDetailInfos);

        return orderListResponse;
    }

    @Override
    public boolean cancelOrderByStatus(String orderId) {

        // 查询订单对应的状态
        Order order = orderMapper.selectByPrimaryKey(orderId);

        // 判断订单的状态

        // 订单为初始化状态， 则取消订单
        if (order.getStatus() == OrderConstants.ORDER_STATUS_INIT) {
            cancelOrder(orderId);
            return true;
        }

        return false;


    }

}
